<template>
  <div
    ref="copyFieldRef"
    class="copy-field__wrapper"
    :class="mouseOver ? 'copy-field-mouse_wrapper' : ''">
    <TextEll
      v-bind="$attrs"
      :class="{ 'cursor-pointer': href }"
      @click="handleClick">
      <slot>{{ content }}</slot>
    </TextEll>

    <span
      v-show="content !== '-' && content !== ''"
      ref="copyIconRef"
      class="copy-icon"
      :class="hoverTable ? 'hover-visible__tr' : ''"
      @click.prevent="handleCopy">
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="14"
        height="14"
        viewBox="0 0 14 14"
        fill="none">
        <path
          fill-rule="evenodd"
          clip-rule="evenodd"
          d="M1 1H10V10H1V1ZM0 0H1H10H11V1V3H13H14V4V13V14H13H4H3V13V11H1H0V10V1V0ZM4 11V12V13H5H12H13V12V5V4H12H11V10V11H10H4Z"
          fill="currentColor" />
      </svg>
    </span>
  </div>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { useClipboard } from '@vueuse/core'

import type { TextEllProps } from './TextEll.vue'

export interface CopyFieldProps extends TextEllProps {
  copyText?: string
  mouseOver?: boolean
  successMessage?: boolean
  hoverTable?: boolean

  href?: string
}

const props = withDefaults(defineProps<CopyFieldProps>(), {
  successMessage: true,
  mouseOver: false,
  hoverTable: false,
  href: 'default'
})
const { copy } = useClipboard({
  legacy: true
})
const copyFieldRef = ref<HTMLElement>()
const router = useRouter()
const handleClick = () => {
  if (props?.href) {
    router.push(props.href)
  }
}
const handleCopy = () => {
  const { textContent } = copyFieldRef.value?.querySelector('.text-ell') || {
    textContent: ''
  }
  const copyContent = props?.copyText || props?.content || textContent || ''

  copy(String(copyContent)).then(() => {
    if (props.successMessage) {
      Message.success('复制成功')
    }
  })
}
</script>

<style lang="less" scoped>
@copy-size: 14px;
.copy-field__wrapper {
  display: flex;
  align-items: center;
  gap: 5px;
  :deep(.text-ell) {
    flex: initial;
    width: max-content;
  }
}
.copy-icon {
  width: @copy-size;
  height: @copy-size;
  color: #bfc2c7;
  cursor: pointer;
  transition: color 0.2s;
  opacity: 0;
  &:hover {
    color: var(--color-text-2) !important;
  }
  svg {
    width: @copy-size;
    height: @copy-size;
  }
}

.arco-table-tr {
  .copy-icon {
    position: absolute;
  }
  &:hover {
    .copy-icon {
      position: relative;
      opacity: 1;
    }
  }
}

.copy-field-mouse_wrapper {
  .copy-icon {
    @apply hidden;
  }

  &:hover {
    .copy-icon {
      @apply inline-block;
    }
  }
}
</style>
